#include "cgps.h"

CGps::CGps(QObject *parent)
    :QObject(parent)
{
    m_pLocation = NULL;
    m_latitude = m_longitude = 0.0;
}

CGps::~CGps()
{
    if (m_pLocation != NULL)
        delete m_pLocation;
}

bool CGps::initialize()
{
    m_pLocation = QGeoPositionInfoSource::createDefaultSource(this);
    if (!m_pLocation)
    {
        // on this platform we do not have a default position source.
        return false;
    }

    // Listen gps position changes
    connect(m_pLocation, SIGNAL(positionUpdated(QGeoPositionInfo)),
            this, SLOT(positionUpdated(QGeoPositionInfo)));

    // in case there exist timeout errors
    connect(m_pLocation, SIGNAL(updateTimeout()),
            this, SLOT(updateTimeout()) );

    return true;
}

void CGps::setUpdateInterval(int milliseconds )
{
    m_pLocation->setUpdateInterval(milliseconds);
}

void CGps::startUpdate()
{
    m_pLocation->startUpdates();
}

void CGps::stopUpdate()
{
    m_pLocation->stopUpdates();
}

// this function is called when we want to update the position
// even when the interval doesnot arrive
void CGps::requestUpdate()
{
    m_pLocation->requestUpdate();
}

void CGps::positionUpdated(const QGeoPositionInfo &gpsPos)
{
    if (gpsPos.isValid()) {
        // get the current position
        QGeoCoordinate coord = gpsPos.coordinate();
        m_latitude = coord.latitude();
        m_longitude = coord.longitude();

        emit positionUpdatedAlready(m_latitude, m_longitude);
   }
}

